class TopicsController < ResourceController
  
  def index
    if params[:search].blank?
      conditions = 'private = 0'
    else
      conditions = ['(topics.name LIKE ? OR posts.content LIKE ?) AND forums.private = 0'] + ['%' + params[:search] + '%'] * 2
    end
    @pager = Pager.new(25, Topic.count(:conditions => conditions, :include => [:posts, :forum]), params[:page])
    @topics = Topic.find_recent(@pager.find_options.merge({ :conditions => conditions}))
  end
  
  def show
    @topic.increment! :view_count
    @pager = Pager.new(posts_per_page, @topic.posts.count, params[:page])
    @posts = @topic.posts.find(:all, @pager.find_options.merge({ :include => [:user, :topic] }))
    respond_to do |wants|
      wants.html  # REFACTORME!  Surely some of this can be simplified
      wants.rss { render_rss_feed_for @topic.posts, :feed => {:title => @topic.name, :link => topic_url(@topic)} }
      wants.atom { render_atom_feed_for @topic.posts, :feed => {:title => @topic.name, :link => topic_url(@topic)} }
      wants.xml { render :xml => @topic.to_xml(:include => :posts) }
    end
  end
  
  def new
    @post = Post.new
  end
  
  def create
    @post = @topic.posts.build(params[:post])
    @post.user = current_user
    if !@topic.valid? || params[:preview_button] # REFACTORME minor duplication with posts controller
      render :action => 'new'
    else
      @topic.save!
      flash[:notice] = "Successfully created topic"
      redirect_to topic_path(@topic)
    end
  end
  
  # render edit
  
  def update
    if @topic.save
      flash[:notice] = "Successfully updated topic"
      redirect_to forum_path(@topic.forum_id)
    else
      render :action => 'edit'
    end
  end
  
  def destroy
    @topic.destroy
    flash[:notice] = "Successfully destroyed topic"
    redirect_to forum_path(@topic.forum_id)
  end
  
  def unanswered
    @pager = Pager.new(25, Topic.count_unanswered, params[:page])
    @topics = Topic.find_unanswered(@pager.find_options)
    render :action => 'index'
  end
  
  def unread
  	unless logged_in?
  		redirect_to :action => 'index'
  	else
	    @pager = Pager.new(25, Topic.count_unread(current_user), params[:page])
	    @topics = Topic.find_unread(current_user, @pager.find_options)
	    render :action => 'index'
	  end
  end
  
  def subscriptions
    @topics = Topic.find_subscriptions(current_user)
    render :action => 'index'
  end
  
  protected
  
    def update_extra_attributes
      @topic.forum_id = params[:forum_id] unless params[:forum_id].nil?
    end
end